package leetcode.Y2024M5D27;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class S61 {
    public ListNode rotateRight(ListNode head, int k) {
        List<Integer> list = new ArrayList<>();
        if (head==null) return head;
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        int endIndex = list.size() - 1;
        k=k%list.size();
        rotate(list, 0, endIndex);
        rotate(list, 0, k - 1);
        rotate(list, k, endIndex);
        ListNode pre = new ListNode(-1);
        ListNode res = pre;
        for (Integer i : list) {
            pre.next = new ListNode(i);
            pre = pre.next;
        }
        return res.next;

    }

    private void rotate(List<Integer> list, int start, int end) {
        while (start < end) {
            int tmp = list.get(start);
            list.set(start, list.get(end));
            list.set(end, tmp);
            start++;
            end--;
        }
    }

    @Test
    public void test() {
        int[] head = {1, 2, 3, 4, 5};
        int k = 2;
        ListNode listNode = ListNode.createListNode(head);
        ListNode listNode1 = rotateRight(listNode, k);
        System.out.println(listNode1);
    }

    @Test
    public void test1() {
        int[] head = {0,1,2};
        int k = 4;
        ListNode listNode = ListNode.createListNode(head);
        ListNode listNode1 = rotateRight(listNode, k);
        System.out.println(listNode1);
    }
}
